(function() {
  var App;
  var lineColor = "#FFD700";
  var lineWidth = 5;
  App = {};
  /*
  	Init 
  */
  App.init = function() {
    App.canvas = document.createElement('canvas');
    App.canvas.height = 300;
    App.canvas.width = 280;
    document.getElementsByTagName('article')[0].appendChild(App.canvas);
    App.ctx = App.canvas.getContext("2d");
    App.ctx.fillStyle = "solid";
    App.ctx.strokeStyle = lineColor;
    App.ctx.lineWidth = lineWidth;
    App.ctx.lineCap = "round";
    App.socket = io.connect('http://192.168.0.11:4000');
    App.socket.on('draw', function(data) {
      return App.draw(data.x, data.y, data.type);
    });
    App.draw = function(x, y, type) {
      if (type === "dragstart") {
        App.ctx.beginPath();
        return App.ctx.moveTo(x, y);
      } else if (type === "drag") {
        App.ctx.lineTo(x, y);
        return App.ctx.stroke();
      } else {
        return App.ctx.closePath();
      }
    };
  };
  /*
  	Draw Events
  */
  $('canvas').live('drag dragstart dragend', function(e) {
    var offset, type, x, y;
    type = e.handleObj.type;
    offset = $(this).offset();
//    e.offsetX = e.layerX - offset.left;
//    e.offsetY = e.layerY - offset.top;
    x = e.offsetX;
    y = e.offsetY;
    App.draw(x, y, type);
    App.socket.emit('drawClick', {
      x: x,
      y: y,
      type: type
    });
  });
  $(function() {
    return App.init();
  });

  $('#reset_canvas').bind("click", function(){
	  App.canvas.width = App.canvas.width;
	  App.ctx.fillStyle = "solid";
	  App.ctx.strokeStyle = lineColor;
	  App.ctx.lineWidth = lineWidth;
	  App.ctx.lineCap = "round";
  });
  
  $('#change_blue').bind("click", function(){changeColor(this);});
  $('#change_red').bind("click", function(){changeColor(this);});
  $('#change_black').bind("click", function(){changeColor(this);});
  $('#change_gold').bind("click", function(){changeColor(this);});
  $('#lineHeightSelectBox').change(function(){lineWidth = this.value;App.ctx.lineWidth = lineWidth;});
  
  function changeColor(e){
	  if(e.id == "change_blue"){
		  App.ctx.strokeStyle = "#0000FF";
		  lineColor = "#0000FF";
	  }else if(e.id == "change_red"){
		  App.ctx.strokeStyle = "#FF0000";
		  lineColor = "#FF0000";
	  }else if(e.id == "change_black"){
		  App.ctx.strokeStyle = "#000000";
		  lineColor = "#000000";
	  }else if(e.id == "change_gold"){
		  App.ctx.strokeStyle = "#FFD700";
		  lineColor = "#FFD700";
	  }
  }
  
}).call(this);

